package client

import (
	"bytes"
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"net/http"

	"gitee.com/zh-jn/harmonica-previewer-online/api"
)

func NewCompileServiceClient(addr string, port int) api.Compiler {
	return &CompileServiceClient{
		Addr: addr,
		Port: port,

		c: &http.Client{},
	}
}

type CompileServiceClient struct {
	Addr string
	Port int

	c *http.Client
}

func (c *CompileServiceClient) Compile(codeBundle []byte) (jsBundle []byte, e error) {
	var rsp *http.Response
	rsp, e = c.c.Post(fmt.Sprintf("http://%v:%v", c.Addr, c.Port), "", bytes.NewReader(codeBundle))
	if e != nil {
		return
	}

	rspbody, err := ioutil.ReadAll(rsp.Body)
	if err != nil {
		e = err
		return
	}

	var jsBundleB64 string
	if e = api.ReadRsp(rspbody, &jsBundleB64); e != nil {
		return
	}

	jsBundle, e = base64.StdEncoding.DecodeString(jsBundleB64)
	return
}
